'''
Created on 23.02.2012

@author: myaut
'''

import os
import signal

import salsa
from salsa import do_trace_interrupt

from salsa.util.io import IOSlave, IOException, IOSlaveCommunicator
from salsa.util.rpc import RPCClient

from salsa.coresvc import CoreClient
from salsa.coresvc.logger import Logger

class TaskException(Exception):
    pass

class Task(CoreClient):
    '''Used for task initialization in task-space'''
    def __init__(self):
        self.taskid = os.getenv('TASK_ID')
        
        if not self.taskid:
            raise TaskException("Couldn't run outside of SALSA service platform. Use salsad")
        
        CoreClient.__init__(self)
        
        self.init_signals()
        
        info = self.core.get_task_info(self.taskid)
        
        # Small hack - sets all task information at once:
        # args, params, port, host
        self.__dict__.update(info)
        
        self.logger = Logger(self.name, self.core_port, self.core_host)
        salsa.logger = self.logger
        
        self.logger.start()
    
    def __del__(self):
        self.stop()
    
    def init_signals(self):
        signal.signal(signal.SIGINT, self.interrupt)
        signal.signal(signal.SIGTERM, self.interrupt)
    
    def interrupt(self, signum, stack):
        do_trace_interrupt()
        
        # self.logger.log(LoggerSeverity.LS_NOTICE, 'Service %s is stopping' % self.name)
        
        self.stop()
    
    def stop(self):
        self.logger.stop()
        
        CoreClient.stop(self)
        
    def invoke(self, name, args = {}):
        self.core.create_task(name, args, self.taskid)